'use strict'

let Fiber = require('fibers');
let http = require('http');

//options = {
//    hostname: '',
//    port: '',
//    path: '',
//    method: ''
//};
function get(options, parameters) {
    let fiber = Fiber.current;
    let error = null;
    let responseContent = null;

    if ( parameters ) {
        let queryString = makeQueryString(parameters);
        if ( queryString ) {
            options.path += '?' + queryString;
        }
    }

    options.method = 'GET';
    var req = http.request(options, function(res) {
        res.on('data', function(d) {
            responseContent = d.toString('utf8');
            fiber.run();
        });
    });
    req.end();

    req.on('error', function(e) {
        error = e;
        fiber.run();
    });

    if ( error ) {
        throw error;
    }

    Fiber.yield();

    return responseContent;
}

function post(options, parameters) {
    let fiber = Fiber.current;
    let error = null;
    let responseContent = null;

    if ( parameters ) {
        let queryString = makeQueryString(parameters);
        if ( queryString ) {
            options.path += '?' + queryString;
        }
    }

    options.method = 'POST';
    var req = http.request(options, function(res) {
        res.on('data', function(d) {
            responseContent = d.toString('utf8');
            fiber.run();
        });
    });
    req.end();

    req.on('error', function(e) {
        error = e;
        fiber.run();
    });

    if ( error ) {
        throw error;
    }

    Fiber.yield();

    return responseContent;
}

function makeQueryString(parameters, options) {
    if ( options ) {
        return makeQueryStringWithOptions(parameters, options);
    }

    let parameterList = [];
    for ( let key in parameters ) {
        let value = parameters[key];

        parameterList.push(key + '=' + value);
    }

    return parameterList.join('&');
}

function makeQueryStringWithOptions(parameters, options) {
    let keyList = Object.keys(parameters).sort();
    let parameterList = keyList.map(key => {
        let value = parameters[key];
        if ( value ) {
            if ( options.urlEncoding) {
                value = encodeURIComponent(value);
            }
            return key + '=' + value;
        }

        return null;
    }).filter(parameter => {
        return parameter != null;
    });

    return parameterList.join('&');
}

module.exports = {
    get: get,
    post: post,
    makeQueryString
};
